package hwOne3;

import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;

// 作业 1.3.12
public class StackIterator<Item> implements Iterable<Item> {
    private Node first; // 栈顶（最近添加的元素）
    private int N;       // 元素数量

    private class Node {
        // 定义了结点的嵌套类
        Item item;
        Node next;
    }
    public boolean isEmpty() { return first == null; }  // 或：N == 0
    public int size() { return N; }
    public void push(Item item) {
        // 向栈顶添加元素
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }
    public Item pop() {
        // 从栈顶删除元素
        Item item = first.item;
        first = first.next;
        N--;
        return item;
    }
    public Item peek() {
        // 从栈顶删除元素
        return first.item;
    }
    public static <Item> StackIterator<Item> copy(StackIterator<Item> source) {
        StackIterator<Item> temp = new StackIterator<>();
        StackIterator<Item> container = new StackIterator<>();
        for( Item sto : source) {
            temp.push(sto);
        }
        for( Item sto : temp) {
            container.push(sto);
        }
        return container;
    }
    public Iterator<Item> iterator() {
        return new StringIterator();
    }
    private class StringIterator implements Iterator<Item> {
        private Node current = first;

        public boolean hasNext() {
            return current != null;
        }

        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

    public static void main(String[] args) {
        StackIterator<String> store = new StackIterator<>();
        store.push("hello");
        store.push("I'm");
        store.push("Jin");

        StackIterator<String>  copyOne = StackIterator.copy(store);
        for( String sto : copyOne) {
            StdOut.println("copy:" + sto);
        }

    }
}
